package tgc.edu.exam.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.DataGridParam;
import tgc.edu.exam.custom.DataGridUtils;
import tgc.edu.exam.custom.LayUiResult;
import tgc.edu.exam.custom.dict.entity.SystemData;
import tgc.edu.exam.custom.dict.entity.SystemDictionaries;
import tgc.edu.exam.custom.dict.service.SystemDataService;
import tgc.edu.exam.custom.dict.service.SystemDicationariesService;
import tgc.edu.exam.entity.Student;
import tgc.edu.exam.entity.SysRole;
import tgc.edu.exam.security.UserUtils;
import tgc.edu.exam.service.StudentService;
import tgc.edu.exam.service.SysRoleService;
import tgc.edu.exam.web.form.StudentForm;
import tgc.edu.exam.web.form.TeacherForm;
import tgc.edu.exam.service.SysFileService;


@RequestMapping(value="/student")
public class StudentController {
	@Autowired
	private StudentService service;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysFileService fileservice;
	@RequestMapping(value="/manage")
	public void manage() {
		
	}
	
	
	public Specification<Student> buildSpec(StudentForm form) {
		Specification<Student> spec=new Specification<Student>() {

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String username = form.getUsername();
				if(StringUtils.hasText(username)) {
					rules.add(cb.like(root.get("username"), "%"+username+"%"));
				}
				String sex = form.getSex();
				if(StringUtils.hasText(sex)) {
					rules.add(cb.equal(root.get("sex"), sex));
				}
				String address = form.getAddress();
				if(StringUtils.hasText(address)) {
					rules.add(cb.like(root.get("address"), "%"+address+"%"));
				}
				String phone = form.getPhone();
				if(StringUtils.hasText(phone)) {
					rules.add(cb.like(root.get("phone"), "%"+phone+"%"));
				}
				String workUnit = form.getWorkUnit();
				if(StringUtils.hasText(workUnit)) {
					rules.add(cb.like(root.get("workUnit"), "%"+workUnit+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	
	
	@RequestMapping(value="/page")
	@ResponseBody
	public Object page(DataGridParam param,StudentForm form) {
		Sort sort=Sort.by("createDate");
		Pageable pageable = param.getPageable(sort);
		Specification<Student> spec = buildSpec(form);
		Page<Student> page = service.findAll(spec, pageable);
		return DataGridUtils.buildResult(page);
	}
	
	
	@RequestMapping(value="/edit")
	public void edit(String id,ModelMap map) {	
		Student model=new Student();
		if(id!=null) {
			model=service.findById(UUID.fromString(id));
		}
		map.put("model", model);
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(StudentForm form) {
		UUID id=form.getId();
		if(id==null) {
			Student student =  service.findByUsername(form.getIdcode());
			if(student!=null) {
				return LayUiResult.getErrorResult("注册失败，此用户已存在");
			}
		}
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		Student model=new Student();
		
		if(id!=null) {
			model=service.findById(id);
			form.setPassword(model.getPassword());
			model.setUpdateDate(sdf.format(new Date()));
			model.setUpdateName(userUtils.getName());
		}else {
			form.setGroup1(false);
			String pwd = form.getIdcode();
			String password = pwd.substring(pwd.length()-6, pwd.length());
			form.setPassword(encoder.encode(password));
			
			SysRole findbyCode = sysRoleService.findbyCode("ROLE_STUDENT");
			model.getRoles().add(findbyCode);
			model.setCreateDate(sdf.format(new Date()));
			model.setCreateName(userUtils.getName());
		}
		form.setUsername(form.getIdcode());
		fileservice.DeleteAll(form.getFileuuid());
		BeanUtils.copyProperties(form, model,"id");
		if(model.getTbClass().getId()==null) {
			model.setTbClass(null);
		}
		service.save(model);
		return LayUiResult.getResult();
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(String id) {
		service.deleteById(UUID.fromString(id));
		return LayUiResult.getResult("删除成功");
	}
	
	@RequestMapping(value="/search")
	public void search(StudentForm form,ModelMap map) {
		map.put("model",form);
	}
	
}
